package ConcurrentHashMapTest;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.BiConsumer;
import java.util.function.Supplier;

public class WordCountHandler {
   public static List<String> list ;
   public static CountDownLatch countDownLatch = new CountDownLatch(5);

    public static Map<String,LongAdder> count(Supplier<Map<String, LongAdder>> supplier , BiConsumer<Map<String,LongAdder> , List<String>> consumer){
        Map<String, LongAdder> map = supplier.get();

//        singleThreadHandler(map , consumer);
        mutiThreadHandler(map,consumer);
        return map ;
    }

    public static void main(String[] args) {
        int input =101;
        int interval = input/5;
        for(int i = 0 ; i < 5 ; i++){
            System.out.println("start:" + i*interval);
            System.out.println("end:" + (i+1)*interval);
        }
        if((4+1)*interval < input){
            System.out.println("end is : " + input);
        }
    }
    private static void singleThreadHandler( Map<String,LongAdder> map , BiConsumer<Map<String,LongAdder> , List<String>> consumer){
        consumer.accept(map, list);
    }
    private static void mutiThreadHandler(Map<String,LongAdder> map , BiConsumer<Map<String,LongAdder> , List<String>> consumer){
        ExecutorService service = Executors.newFixedThreadPool(5);
        int start = 0 ;
        int end = 0 ;
        int interval = list.size()/5;
        for(int i = 0 ; i < 5 ; i++){
            start = i*interval;
            if(i < 5){
                end = start + interval;
            }else if( ((4+1)*interval) < list.size()){
                end = list.size() - 1 ;
            }

            service.execute(new Handler(start,end,consumer ,  map));
        }
        try {
            countDownLatch.await();
            service.shutdownNow();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static class Handler implements Runnable{
        private Map<String, LongAdder> map;
        private int start ;
        private int end;
        private BiConsumer<Map<String,LongAdder> , List<String>> consumer;
        public Handler(int start , int end , BiConsumer<Map<String,LongAdder> , List<String>> consumer , Map<String,LongAdder> map ){
           this.start = start ;
           this.end = end ;
           this.consumer = consumer ;
           this.map = map ;
        }
        @Override
        public void run() {
            List<String> strings = list.subList(start, end);
            consumer.accept(map ,strings);
            countDownLatch.countDown();
        }
    }
}
